package com.ctsi.offlinesupport.service;


import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.exception.ExceptionFactory;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.offlinesupport.dto.MeetRecordDTO;
import com.ctsi.offlinesupport.dto.SupportResultDTO;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.supportflow.app.entity.SupportTask;
import org.flowable.engine.HistoryService;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * SupportTask Service 类
 * @author   liuhx
 * @description  SupportTask
 * @created	 Mon Oct 29 12:00:15 CST 2018
 */
@Service
public class SupportTaskService {
	private static final Logger logger=LoggerFactory.getLogger(SupportTaskService.class);
	@Autowired
	private MybatisGenericDao dao;
	@Autowired
    private ExceptionFactory exceptionFactory;
	/**
	 * 添加
	 */
	public void insertSupportTask(SupportTask supportTask){
		if(UtilValidate.isEmpty(supportTask.getTaskId())) {
			logger.error("supportTask sub from taskId can not be null");
			exceptionFactory.throwInternalError();
		}
		logger.debug("insert {}",supportTask);
		dao.insert(supportTask);
	}
	/**
	 * 动态更新
	 */
	public int updateSupportTaskByPKSelective(SupportTask supportTask){
		logger.debug("updateByPrimaryKeySelective {}",supportTask);
		return dao.update(SupportTask.class.getName()+".updateByPrimaryKeySelective", supportTask);
	}
	/**
	 * 更新
	 */
	public int updateSupportTask(SupportTask supportTask){
		logger.debug("update {}",supportTask);
		return dao.update(supportTask);
	}


	public SupportTask editSupportTaskById(String id){
		if(UtilValidate.isEmpty(id)) {
			return null;
		}
		logger.debug("editById {}",id);
		return (SupportTask)dao.queryForObject(SupportTask.class.getName()+".edit", id);
	}
	/**
	 * 根据ID查找 SupportTask对象
	 */
	public SupportTask findSupportTaskById(String id){
		if(UtilValidate.isEmpty(id)) {
			return null;
		}
		logger.debug("findById {}",id);
		return dao.get(SupportTask.class, id);
	}
	/**
	 * 删除SupportTask对象
	 */
	public int removeSupportTask(String id){
		if(UtilValidate.isNotEmpty(id)) {
			return dao.delete(SupportTask.class.getName()+".delete", id);
		}
			//return dao.remove(id);
		return 0;
	}

	/**
	 * 详细页查询
	 */
	public Map<String,Object> findByDetail(String id){
		return (Map<String,Object>)dao.queryForObject(SupportTask.class.getName()+".findByDetail",id);
	}
	/**
	 * 多条件查询结果
	 */
	public Page<Map<String,Object>> findByMulitCondition(Map<String,Object> param , int start , int pageSize){
		logger.debug("findByMulitCondition {}",param);
		if(pageSize<0||pageSize>2000) {
			pageSize=Page.DEFAULT_PAGE_SIZE;
		}
		if(start!=-1) {
			return dao.queryPage(SupportTask.class.getName()+".selectMulitCondition", param, start, pageSize);
		} else{
			throw new RuntimeException("参数不正确 !!");
		}
	}
	/**
	 * 多条件查询结果不分页
	 */
	public List<?> find(Map<String,Object> map){
		logger.debug("find {}",map);
		return dao.queryForList(SupportTask.class.getName()+".selectByMap",map);
	}

    /**
     * 获取支撑任务
     * @param taskId
     * @param userId
     * @return
     */
	public SupportTask findSupportTaskByUser (String taskId,String userId) {
       return (SupportTask) dao.queryForObject(SupportTask.class.getName()+".selectMulitCondition",new HashMap<String,Object>(){{
            this.put("taskId",taskId);
            this.put("supportUserId",userId);
        }});
    }

    private PersonServiceProxy userServiceProxy;

    public PersonServiceProxy getUserServiceProxy() {
        if (userServiceProxy == null ) {
            return  this.userServiceProxy = OrganiseFactoryBean.getInstance().getPersonServiceProxy();
        }
        return this.userServiceProxy;
    }

    @Autowired
	private HistoryService historyService;

    /**
     *	获取所有沟通记录
     * @param processInstId
     * @return
     */
    public List<MeetRecordDTO> findAllSupportRecords(String processInstId){
		String bk = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstId).singleResult().getBusinessKey();
        List<MeetRecordDTO> dtos = (List<MeetRecordDTO>) dao.queryForList(SupportTask.class.getName()+".findAllRecord",bk);
        if (UtilValidate.isEmpty(dtos)) {
            return new ArrayList<>(0);
        }
       return dtos;
    }

    /**
     * 获取已经接单的专家列表
     * @param processInstId
     * @return
     */
    public List<SupportTask> findAllAssterTask(String processInstId,int userRoleType){
        return (List<SupportTask>) dao.queryForList(SupportTask.class.getName()+".querySupportByType",new HashMap<String,Object>(){{
            put("processInstId",processInstId);
            put("userRoleType",userRoleType);
        }});
    }

	/**
	 * 只是为了兼容一期的老数据
	 * @param businessKey
	 * @param userRoleType
	 * @return
	 */
    public List<SupportTask> findAllAssterTaskByBk(String businessKey,int userRoleType){
		return (List<SupportTask>) dao.queryForList(SupportTask.class.getName()+".querySupportByType",new HashMap<String,Object>(){{
			put("businesskey",businessKey);
			put("userRoleType",userRoleType);
		}});
	}

	/**
	 * 获取指定类型和状态的支撑人员，包括专家
	 * @param taskId
	 * @param userRoleType
	 * @param taskStatus
	 * @return
	 */
	@Deprecated
    public List<SupportTask> findAllSupportorTask(String taskId,int userRoleType,int taskStatus ){
        return (List<SupportTask>) dao.queryForList(SupportTask.class.getName()+".selectMulitCondition",new HashMap<String,Object>(){{
            put("taskId",taskId);
            put("userRoleType",userRoleType);
            put("taskStatus",taskStatus);
        }});
    }

    public List<SupportResultDTO> findAllSupportTaskDTO(String taskId,int userRoleType,int taskStatus){

		return (List<SupportResultDTO>) dao.queryForList(SupportTask.class.getName()+".findAllSupportAndAsster",new HashMap<String,Object>(){{
			put("taskId",taskId);
			put("userRoleType",userRoleType);
			put("taskStatus",taskStatus);
		}});
	}

	/**
	 * 自动办结拉去信息
	 * @param businesskey
	 * @return
	 */
	public List<SupportResultDTO> findAllSupportTaskDTO4AutoEnd(String businesskey){

		return (List<SupportResultDTO>) dao.queryForList(SupportTask.class.getName()+".findAllSupportAndAsster4AutoEnd",new HashMap<String,Object>(){{
			put("businesskey",businesskey);
			put("userRoleType",1);
			put("taskStatus",2);
		}});
	}


	/**
	 * 只是为了更新4月份的及时率
	 */
	public void update4yuejslv(){
		List<SupportTask> tasks = (List<SupportTask>) dao.queryForList(SupportTask.class.getName()+".query4yuefenjslv");
		tasks.stream().forEach( task -> {
			HistoricTaskInstance his = historyService.createHistoricTaskInstanceQuery().taskId(task.getTaskId()).singleResult();
			Date date = his.getStartTime();
			long last = timeUtil.getLastHandlerTime(date,60);
			task.setLastHandlerTime(last);
			logger.warn(UtilDateTime.toDateString(date) + "=======================" + UtilDateTime.longToString(last));
			task.setTimely( task.getApplyTime() > task.getLastHandlerTime() ? 0 : 1 );
			this.updateSupportTaskByPKSelective(task);
		});

	}

	@Autowired
	private TimeUtil timeUtil;
}
